package com.resource.project.service.system.service.impl;

import com.resource.base.config.jwt.TokenProvider;
import com.resource.project.entity.system.Hr;
import com.resource.project.os.AskToken;
import com.resource.project.os.LoginVo;
import com.resource.project.service.system.service.IHrService;
import com.resource.project.service.system.service.ILoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenProvider tokenProvider;
    @Autowired
    private IHrService hrService;
    @Override
    public AskToken getAskTokenByLogin(LoginVo loginVM) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = loginVM.getRememberMe() == null ? false : loginVM.getRememberMe();
        Hr hr = hrService.getByAccount(loginVM.getUsername());
        String token = this.tokenProvider.createToken(authentication, rememberMe);
        System.err.println(token);
        log.info("登录生成token:{}", token);
        AskToken askToken = new AskToken(token, this.tokenProvider.getExpirationDateSecondsFromToken(token));
        askToken.setHr(hr);
        return askToken;
    }
}
